<template>
    <div class="login">
        <!-- 这是登录组件<i class="iconfont iconweixin"></i> -->
        <div class="close">
            <i class="iconfont iconicon-test"></i>
        </div>
        <div class="logo">
            <i class="iconfont iconnew"></i>
        </div>
        <div class="username">
              <hm-input :rules="userRule" err-msg="请输入正确的账号(5-11位的数字)" v-model="username" placeholder="请输入用户账号(手机号)"></hm-input>
        </div>
        <div class="password">

            <hm-input :rules="passRule" err-msg="请输入密码(必须3-12位的字符)" v-model="password" type="password" placeholder="请输入密码"></hm-input>
        </div>
        <div class="login-btn">
            <hm-button @click="login">登录</hm-button>

        </div>
        <div class="go-register">
            没有账号？立即<router-link to="/register">注册</router-link>
        </div>
    </div>
</template>

<script>

import HmInput from 'components/hm-input.vue'
import HmButton from 'components/hm-button.vue'

export default {
  data () {
    return {
      username: '',
      password: '',
      userRule: /^1\d{4,10}$/,
      passRule: /^\w{3,12}$/
    }
  },
  components: {
    HmButton,
    HmInput
  },
  created () {
    const { username, password } = this.$route.params
    if (username && password) {
      this.username = username
      this.password = password
    }
  },
  methods: {
    async login () {
    //   console.log(this.username, this.password)
      if (!this.userRule.test(this.username)) {
        this.$toast('请输入正确的手机号/账号')
        return
      }
      if (!this.passRule.test(this.password)) {
        this.$toast('请输入正确的密码')
        return
      }
      const res = await this.$axios.post('/login', {
        username: this.username,
        password: this.password
      })
      const { statusCode } = res.data
      if (statusCode === 200) {
        this.$toast.success('登录成功')
        const { token, user } = res.data.data
        localStorage.setItem('token', token)
        localStorage.setItem('user_id', user.id)

        this.$router.push('/')
      } else {
        this.$toast.fail('用户名或密码错误')
      }
    }
  }
}

</script>

<style lang="scss" scoped>
.login {
    padding: 20px;
    .closs{
        i {
            font-size:27px;
        }
    }
    .logo {
        text-align: center;
        i {
            font-size:126px;
            color: #d81e06
        }
    }
    .login-btn {
    margin-top: 15px;

    .test {
      background-color: orange;
      border: 1px solid orange;
      border-radius: 5px;
    }
  }
  .go-register {
    font-size: 16px;
    text-align: center;
    padding-top: 20px;
    a {
      color: blue;
    }
  }
}

</style>
